#!/bin/bash
set -e
if [ -z $1 ];then
        echo "请输入Docker服务器主机名"
        #exit 0
fi
HOST=*
mkdir -p /opt/cert/docker
cd /opt/cert/docker
#创建ca密钥
openssl genrsa -aes256 -out ca-key.pem 4096
#创建ca证书
openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem
#创建服务器私钥
openssl genrsa -out server-key.pem 4096
#签名私钥
openssl req -subj "/CN=$HOST" -sha256 -new -key server-key.pem -out server.csr
# 配置白名单，推荐配置0.0.0.0，允许所有IP连接但只有证书才可以连接成功
echo subjectAltName = IP:172.17.0.1,IP:172.18.158.68,IP:127.0.0.1,IP:47.119.120.197,DNS:* > extfile.cnf
#echo subjectAltName = DNS:$HOST,IP:0.0.0.0 > extfile.cnf
#使用ca证书与私钥证书签名
openssl x509 -req -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -extfile extfile.cnf
#生成客户端密钥
openssl genrsa -out key.pem 4096
#签名客户端
openssl req -subj '/CN=client' -new -key key.pem -out client.csr
#创建配置文件
echo extendedKeyUsage = clientAuth > extfile.cnf
#签名证书
openssl x509 -req -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem -extfile extfile.cnf
rm -v client.csr server.csr
#授权
chmod -v 0400 ca-key.pem key.pem server-key.pem
chmod -v 0444 ca.pem server-cert.pem cert.pem

